import { createCookie } from "@remix-run/node";
import { RemixI18Next } from "remix-i18next/server";
import Backend from "i18next-fs-backend";
import { i18nConfig } from "./config";
import { createInstance } from "i18next";
import { initReactI18next } from "react-i18next";
import { resolve } from "node:path";

export const i18nCookie = createCookie("_i18n", {
  path: "/",
  sameSite: "lax",
  httpOnly: true,
  maxAge: 60, // 1 minute - We do not require a long session for i18n.
  secrets: [process.env.SESSION_SECRET || "SESSION_SECRET"],
  secure: process.env.NODE_ENV === "production",
});

export const remixI18Next = new RemixI18Next({
  detection: {
    cookie: i18nCookie,
    supportedLanguages: i18nConfig.supportedLngs,
    fallbackLanguage: i18nConfig.fallbackLng,
  },
  i18next: {
    ...i18nConfig,
    backend: {
      loadPath: resolve("./public/locales/{{lng}}/{{ns}}.json"),
    },
  },
  backend: Backend,
});

export async function getServerI18n(lng: string, ns: string[]) {
  const instance = createInstance();

  await instance
    .use(initReactI18next)
    .use(Backend)
    .init({
      ...i18nConfig,
      lng,
      ns,
      backend: {
        loadPath: resolve("./public/locales/{{lng}}/{{ns}}.json"),
      },
      interpolation: {
        escapeValue: false,
      },
      react: {
        useSuspense: false,
      },
      initImmediate: false,
    });

  return instance;
}
